import java.util.*;

public class Main {

    //
    //
    //        0
    //       / \
    //      1   2
    //     / \ / \
    //    4   5   6
    //   / \ /  \/  \
    //  7   3    8    9
    //   \       | \  /
    //    10     |  11
    //      \    |  /
    //          12

    public final static List<Link> links = Arrays.asList(
            new Link("0", "1"),
            new Link("0", "2"),
            new Link("1", "4"),
            new Link("1", "5"),
            new Link("2", "5"),
            new Link("2", "6"),
            new Link("4", "7"),
            new Link("4", "3"),
            new Link("5", "3"),
            new Link("5", "8"),
            new Link("6", "8"),
            new Link("6", "9"),
            new Link("7", "10"),
            new Link("10", "12"),
            new Link("8", "11"),
            new Link("9", "11"),
            new Link("8", "12"),
            new Link("11", "12")
    );


    List<Link> watch = new ArrayList<>();

    public static void main(String[] args) {


        new Main();
    }

    public synchronized void addToWatch(Link link) {
        watch.add(link);


        List<Link> brotherNode = Utils.getLinkTargetIs(link.target);
        boolean canRun = true;
        for (Link oneNode : brotherNode) {
            canRun = canRun && watch.contains(oneNode);
        }
        if (canRun) {
            System.out.println("Thread"+Thread.currentThread().getId()+":"+link + " all brother's father is ok , then ok to run");
            runLink(link, true);
        }else{
            System.out.println("Thread"+Thread.currentThread().getId()+":"+link + " all brother's father is not ok , then wait");
        }
    }


    private Main() {


        List<Link> roots = Utils.getLinkSourceIs("0");


        for (Link root : roots) {

            runLink(root, false);

        }

    }


    private void runLink(Link link, boolean ignoreBrother) {

        DriveLink driveLink = new DriveLink(link, new DriveLink.LinkFinishListener() {
            @Override
            public void onLinkFinish(Link currentLink, List<Link> nextLinks) {
                System.out.println("Thread"+Thread.currentThread().getId()+":"+currentLink + " finished!");

                if (nextLinks.size() == 0) {
                    System.out.println("Thread"+Thread.currentThread().getId()+":"+"here to check all link is finished.....");
                }

                for (Link link1 : nextLinks) {
                    runLink(link1, false);
                }
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                driveLink.runIt(Main.this, ignoreBrother);
            }
        }).start();

    }


}
